package com.mxun.winefox.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cached
import androidx.compose.material.icons.filled.VolumeUp
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.mxun.winefox.data.ChatMessage

@Composable
fun ChatMessageItem(
    message: ChatMessage,
    playingMessage: String?,
    isTTSPlaying: Boolean,
    isBilingualDisplay: Boolean,
    isJapaneseVoice: Boolean,
    hasCachedAudio: Boolean,
    onPlayMessage: (ChatMessage) -> Unit,
    onRefreshMessage: (ChatMessage) -> Unit
) {
    val textToShow = if (!message.fromUser && isBilingualDisplay && message.ttsContent != null) {
        "${message.displayContent}\n${message.ttsContent}"
    } else {
        message.displayContent
    }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = if (message.fromUser) Arrangement.End else Arrangement.Start
    ) {
        Column(
            horizontalAlignment = if (message.fromUser) Alignment.End else Alignment.Start
        ) {
            Box(
                modifier = Modifier
                    .background(
                        if (message.fromUser) MaterialTheme.colorScheme.primaryContainer
                        else MaterialTheme.colorScheme.secondaryContainer,
                        RoundedCornerShape(12.dp)
                    )
                    .padding(12.dp)
            ) {
                Text(
                    text = textToShow,
                    fontSize = 16.sp,
                    color = if (message.fromUser) MaterialTheme.colorScheme.onPrimaryContainer
                    else MaterialTheme.colorScheme.onSecondaryContainer
                )
            }

            if (!message.fromUser) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(top = 4.dp)
                ) {
                    Text(
                        "酒狐",
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                        modifier = Modifier.padding(end = 4.dp)
                    )

                    // 播放按钮
                    IconButton(
                        onClick = { onPlayMessage(message) },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            Icons.Default.VolumeUp,
                            contentDescription = "播放语音",
                            tint = if (playingMessage == message.displayContent && isTTSPlaying)
                                MaterialTheme.colorScheme.primary
                            else if (hasCachedAudio)
                                MaterialTheme.colorScheme.primary.copy(alpha = 0.7f)
                            else
                                MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                        )
                    }

                    // 刷新按钮（仅当有缓存时显示）
                    if (hasCachedAudio) {
                        IconButton(
                            onClick = { onRefreshMessage(message) },
                            modifier = Modifier.size(24.dp)
                        ) {
                            Icon(
                                Icons.Default.Cached,
                                contentDescription = "重新获取语音",
                                tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun ChatHistory(
    chatHistory: List<ChatMessage>,
    playingMessage: String?,
    isTTSPlaying: Boolean,
    isBilingualDisplay: Boolean,
    isJapaneseVoice: Boolean,
    cachedMessages: Set<String>,
    onPlayMessage: (ChatMessage) -> Unit,
    onRefreshMessage: (ChatMessage) -> Unit,
    modifier: Modifier = Modifier,
) {
    LazyColumn(
        modifier = modifier.fillMaxSize(),
        reverseLayout = true,
        contentPadding = PaddingValues(vertical = 8.dp)
    ) {
        items(chatHistory.reversed()) { message ->
            // 统一缓存键计算方式
            val cacheKey = if (isJapaneseVoice) message.ttsContent else message.displayContent

            ChatMessageItem(
                message = message,
                playingMessage = playingMessage,
                isTTSPlaying = isTTSPlaying,
                isBilingualDisplay = isBilingualDisplay,
                isJapaneseVoice = isJapaneseVoice,
                hasCachedAudio = cacheKey != null && cachedMessages.contains(cacheKey),
                onPlayMessage = onPlayMessage,
                onRefreshMessage = onRefreshMessage
            )
        }
    }
}